import RightFixed from '@/layouts/RightFixed';
import TopBread from '@/layouts/TopBread';
import { getAllCar, removeWillBuy, updQty } from '@/services/shopCar';
import { colorStr, getQueryParams } from '@/utils/utils';
import { Button, Empty, InputNumber, message, Table, Tooltip } from 'antd';
import { useCallback, useEffect, useState } from 'react';
import { history } from 'umi';
import AddressConfirm from './components/AddressConfirm';
import { COLUMNS } from './constants';
import styles from './index.less';

const ShopCar: React.FC = () => {
  const { lastRoute }: any = history?.location?.query;
  const [willBuy, setWillBuy] = useState<any[]>([]);
  const qs = getQueryParams();
  // 主题颜色的值
  const [color, setColor] = useState<string>(localStorage.getItem('color') || '#1a7721');
  const [qtyValueObj, setQtyValueObj] = useState<any>({});
  const [addressModal, setAddressModal] = useState<boolean>(false);
  const [moneyCount, setMoneyCount] = useState<number>(0);
  const [list, setList] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);

  useEffect(() => {
    let moneyCurrent = 0;
    willBuy.map((item: any) => {
      moneyCurrent = moneyCurrent + item.price * item.qty;
    });
    setMoneyCount(moneyCurrent);
  }, [willBuy]);

  // 分页的方法
  const handlePageChange = (page: any) => {
    setCurrentPage(page);
  };

  const getList = useCallback(async () => {
    try {
      const res = await getAllCar({ pageIndex: currentPage, userid: qs.id });
      setTotal(res.total);
      setList(res.list);
    } catch (error) {
      console.error(error);
    }
  }, [currentPage, qs.id]);

  const removeShop = async (shopId: string) => {
    try {
      await removeWillBuy({ id: shopId }).then(() => {
        getList();
        message.success('删除成功！');
      });
    } catch (error) {
      console.log(error);
    }
  };

  const updQtyById = async (shopId: string, value: any) => {
    try {
      await updQty({ id: shopId, qty: value }).then(() => {
        getList();
      });
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getList();
  }, [getList]);

  // 放置选中的table行
  const selectedRow = async (selectedRowKeys: React.Key[], selectedRows: any[]) => {
    let currentArr: any[] = [];
    selectedRows.map((item) => {
      currentArr.push(item);
    });
    setWillBuy(currentArr);
  };

  const goodsQtyChange = async (value: any, bKey: any) => {
    list.forEach((item) => {
      if (item.id === bKey.id) {
        qtyValueObj[bKey.id] = value;
      }
      setQtyValueObj({ ...qtyValueObj });
    });

    let moneyCurrent = 0;
    await willBuy.map((item) => {
      if (bKey.id === item.id) {
        moneyCurrent = moneyCurrent + bKey.price * value;
      } else {
        moneyCurrent = moneyCurrent + item.price * item.qty;
      }
    });
    setMoneyCount(moneyCurrent);
    updQtyById(bKey.id, value);
  };

  const rowSelection = {
    renderCell(checked: any, record: any, index: any, node: any) {
      if (record.stock < record.qty) {
        return <Tooltip title="库存不足">{node}</Tooltip>;
      } else if (record.stock === record.qty) {
        return <Tooltip title={`该商品当前库存为${record.stock}`}>{node}</Tooltip>;
      }
      return node;
    },
    onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
      selectedRow(selectedRowKeys, selectedRows);
    },
    getCheckboxProps: (record: any) => {
      let checkboxProps = { disabled: false };
      if (record.stock < record.qty) {
        checkboxProps.disabled = true;
      }

      return checkboxProps;
    },
  };

  const columns = COLUMNS.map((item: any) => {
    let columnsItem = item;
    if (item.key === 'title') {
      columnsItem.render = (_: any, b: any) => {
        return (
          <div
            className={styles.goodsmessage}
            key={item.key}
            onClick={() => {
              // let pushQs = { ...b, ...business };
              history.push({
                pathname: '/commodity',
                query: { lastRoute: '购物车', id: b.commodityId },
              });
            }}
          >
            {b.title}
          </div>
        );
      };
    }
    if (item.key === 'imgs') {
      columnsItem.render = (_: any, record: any) => {
        console.log(record.img[0]);

        return (
          <img
            alt={''}
            key={record.id}
            style={{ width: 124, margin: '0 auto' }}
            src={`http://localhost:8090/dyh/upload_images/commodity/${JSON.parse(record.img)[0]}`}
          />
        );
      };
    }
    if (item.key === 'action') {
      columnsItem.render = (_: any, record: any) => {
        return (
          <div className={styles.action} key={item.key}>
            <span
              style={{
                border: colorStr(5),
                borderRadius: 3,
                padding: '5px 15px',
                cursor: 'pointer',
              }}
              onClick={() => {
                removeShop(record.id);
              }}
            >
              删除
            </span>
          </div>
        );
      };
    }
    if (item.key === 'qty') {
      columnsItem.render = (_: any, b: any) => {
        return (
          <InputNumber
            key={b.key}
            min={1}
            max={b.stock}
            value={qtyValueObj[b.key] || b.qty}
            onChange={(value) => goodsQtyChange(value, b)}
          />
        );
      };
    }
    if (item.key === 'price') {
      columnsItem.render = (a: any, b: any) => {
        return <span key={b.key}>{b.price ? b.price.toFixed(2) : ''}</span>;
      };
    }
    if (item.key === 'amount') {
      columnsItem.render = (a: any, b: any) => {
        return (
          <div key={b.key}>
            {(qtyValueObj[b.key] ? b.price * qtyValueObj[b.key] : b.price * b.qty).toFixed(2)}
          </div>
        );
      };
    }
    return item;
  });

  return (
    <div className={styles.container}>
      <TopBread lastRoute={lastRoute} now={'购物车'} setColorParent={setColor} />
      <div className={styles.contentStyle}>
        {!list[0] ? (
          <div
            className={styles.emptyDiv}
            style={{
              backgroundColor: colorStr(1),
            }}
          >
            <Empty
              image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
              imageStyle={{ height: 80 }}
              description={
                <span
                  style={{
                    color: colorStr(6),
                  }}
                >
                  您还没有选购任何商品，快点击下方按钮前去购买吧！
                </span>
              }
            >
              <Button
                style={{ color: color }}
                onClick={() => {
                  history.push({
                    pathname: '/goodsPage',
                    query: { lastRoute: '购物车' },
                  });
                }}
              >
                前去购买
              </Button>
            </Empty>
          </div>
        ) : (
          <div className={styles.content}>
            <Table
              className={styles.contentTable}
              columns={columns}
              // 按id筛重（rowKey）
              rowKey="id"
              dataSource={list}
              rowSelection={{ type: 'checkbox', ...rowSelection }}
              style={{
                backgroundColor: colorStr(1),
              }}
              bordered // 表格的border
              pagination={{
                total,
                current: currentPage, // 当前页数
                pageSize: 10, // 每页条数
                size: 'small', // 分页的样式
                hideOnSinglePage: true, // 只有一页时是否隐藏分页器
                onChange: handlePageChange, // 分页的方法
              }}
            />
            <div
              className={styles.calcDiv}
              style={{
                backgroundColor: colorStr(3),
              }}
            >
              <Button
                className={styles.calculation}
                style={{
                  backgroundColor: colorStr(2),
                }}
                onClick={() => {
                  setAddressModal(true);
                }}
                disabled={willBuy.length === 0}
              >
                结算
              </Button>
              <span className={styles.count}>合计： {moneyCount.toFixed(2)}</span>
            </div>
          </div>
        )}
      </div>
      <RightFixed color={color} thisRoute={'购物车'} />
      <AddressConfirm
        visible={addressModal}
        onCancel={() => {
          setAddressModal(false);
        }}
        moneyCount={moneyCount.toFixed(2)}
        willBuy={willBuy}
        getCarList={getList}
      />
    </div>
  );
};

export default ShopCar;
